import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:orginone/components/CommandWidget/index.dart';
import 'package:orginone/config/constant.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/log/log_util.dart';
import 'package:path_provider/path_provider.dart';

import '../../../../dart/base/common/commands.dart';
import '../../../../dart/base/ui.dart';
import '../../../XStatefulWidget/XStatefulWidget.dart';

class PDFReaderPage extends XStatefulWidget<FileItemShare> {
  PDFReaderPage({super.key});

  @override
  State<PDFReaderPage> createState() => _PDFReaderPageState();
}

class _PDFReaderPageState extends XStatefulState<PDFReaderPage, FileItemShare> {
  ///总页数
  int? totalPage = 0;

  ///当前页 第一页下标为0
  int? currentPage = 0;
  bool isReady = false;
  bool pathReady = false;
  String errorMessage = '';
  late FileItemShare fileModel;
  String? path;

  @override
  void initState() {
    ///获取路由传参
    fileModel = RoutePages.getPageParams;
    createFileOfPdfUrl().then((f) {
      path = f.path;
      pathReady = true;
      command.emitterFlag('readPdf');
      // update(["pdf_reader_page"]);
    });
    // update(["pdf_reader_page"]);
    super.initState();
  }

  @override
  Widget buildWidget(BuildContext context, dynamic data) {
    return CommandWidget(
      flag: 'readPdf',
      builder: (context, data) {
        return _buildView();
      },
    );
    // return XScaffold(
    //   titleName: fileModel.name ?? "",
    //   body: SafeArea(
    //     child: _buildView(),
    //   ),
    //   floatingActionButton: FutureBuilder<PDFViewController>(
    //     // future: future,
    //     builder: (context, AsyncSnapshot<PDFViewController> snapshot) {
    //       if (snapshot.hasData) {
    //         return FloatingActionButton.extended(
    //           label: _floatView(snapshot),
    //           onPressed: () {},
    //         );
    //       }

    //       return Container();
    //     },
    //   ),
    // );
  }

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        _pdfView(),
        errorMessage.isEmpty
            ? !isReady
                ? const Center(
                    child: CircularProgressIndicator(),
                  )
                : Container()
            : const Center(
                child: Padding(
                  padding: EdgeInsets.all(15.0),
                  child: Text('无法识别PDF文件类型或者文件已损坏'),
                ),
              )
      ],
    );
  }

  _pdfView() {
    return pathReady
        ? PDFView(
            filePath: path,
            // enableSwipe: false,
            // swipeHorizontal: true,
            autoSpacing: false,
            pageFling: true,
            pageSnap: true,
            defaultPage: currentPage!,
            fitPolicy: FitPolicy.BOTH,
            preventLinkNavigation: false,
            onRender: (pages) => onRender(pages),
            onError: (error) => onError(error),
            onPageError: (page, error) => onPageError(page, error),
            onViewCreated: (PDFViewController pdfViewController) =>
                onViewCrweated(pdfViewController),
            onLinkHandler: (String? uri) => onLinkHandler(uri),
            onPageChanged: (int? page, int? total) =>
                onPageChanged(page, total))
        : Container();
  }

  @override
  Widget getSubTitle(BuildContext context, IEntityUI? entity) {
    return Text('(${currentPage! + 1}/${totalPage!})');
  }

  _floatView(AsyncSnapshot<PDFViewController> snapshot) {
    return Column(
      children: [
        Row(
          children: [
            GestureDetector(
              child: const Icon(Icons.arrow_left),
              onTap: () => previousPage(snapshot),
            ),
            Text(" ${currentPage! + 1}/${totalPage!}"),
            GestureDetector(
              child: const Icon(Icons.arrow_right),
              onTap: () => nextPage(snapshot),
            ),
          ],
        )
      ],
    );
  }

  ///pdf加载完成
  onRender(int? pages) {
    totalPage = pages;
    isReady = true;
    XLogUtil.i('onRender: $pages');
    // update(["pdf_reader_page"]);
    setState(() {});
  }

  ///页面切换
  onPageChanged(int? page, int? total) {
    XLogUtil.i('page change: $page/$total');
    currentPage = page!;
    // update(["pdf_reader_page"]);
    setState(() {});
  }

  ///链接跳转
  onLinkHandler(String? uri) {
    XLogUtil.i('goto uri: $uri');
    // update(["pdf_reader_page"]);
    setState(() {});
  }

  ///pdf加载完成
  onViewCrweated(PDFViewController pdfViewController) {
    // pdfcontroller.complete(pdfViewController);
    // update(["pdf_reader_page"]);
    setState(() {});
  }

  ///pdf加载错误
  onPageError(int? page, error) {
    errorMessage = '$page: ${error.toString()}';
    // update(["pdf_reader_page"]);
    XLogUtil.i('$page: ${error.toString()}');
    setState(() {});
  }

  ///pdf加载错误
  onError(error) {
    errorMessage = error.toString();
    // update(["pdf_reader_page"]);
    XLogUtil.i(error.toString());
    setState(() {});
  }

  //跳转页码
  nextPage(AsyncSnapshot<PDFViewController> snapshot) async {
    if (currentPage! < totalPage!) {
      await snapshot.data!.setPage(currentPage! + 1);
    }
  }

  ///上一页
  previousPage(AsyncSnapshot<PDFViewController> snapshot) async {
    if (currentPage! > 0) {
      // update(["pdf_reader_page"]);
      await snapshot.data!.setPage(currentPage! - 1);
      setState(() {});
    }
  }

  ///从网络加载PDF
  Future<File> createFileOfPdfUrl() async {
    Completer<File> completer = Completer();
    XLogUtil.i("Start download file from internet!");
    try {
      final url = '${Constant.host}${fileModel.shareLink}';
      final filename = url.substring(url.lastIndexOf("/") + 1);
      var request = await HttpClient().getUrl(Uri.parse(url));
      var response = await request.close();
      var bytes = await consolidateHttpClientResponseBytes(response);
      var dir = await getApplicationDocumentsDirectory();
      XLogUtil.i("Download files");
      XLogUtil.i("${dir.path}/$filename");
      var tmpFileName = filename.hashCode;
      XLogUtil.i("${dir.path}/$tmpFileName");
      File file = File("${dir.path}/$tmpFileName");

      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file!');
    }

    return completer.future;
  }
}
